import { memo, useCallback, useRef, useState } from "react"
import { BaseContiner, TableContainer, TableHeader } from "../../../csscomponents/base";
import { Button, Col, Flex, Form, Input, Modal, Row, Space, Table } from "antd";
import { ErrorBox } from "../../../components/error-box";
import { IArticle, IArticleSearchParams, useDeletedArticle, useGetArticle } from "../../../service/article-service";
import { useForm } from "antd/es/form/Form";
import { IFormRef } from "../../../types";
import {
    PlusOutlined
} from '@ant-design/icons';
import ArticleForm from "./article-form";

const ArticlePage = () => {
    const defaultQueryParams: IArticleSearchParams = {
        articleTitle: "",
        recommend: null,
        page: 1,
        limit: 10
    }
    const [queryForm] = useForm();
    const [open, setOpen] = useState<boolean>(false);
    const [updateArticle, setUpdateArticle] = useState<IArticle>();
    const FormRef = useRef<IFormRef>();
    const openFn = useCallback((open: boolean) => {
        setOpen(open)
    }, [])
    /**
     * 搜索参数
     */
    const [queryParams, setQueryParams] = useState<IArticleSearchParams>(defaultQueryParams)


    /**
     * 搜索Handler
     * @param values 搜索参数
     */
    const onFinish = (values: { articleTitle: string, recommend: number }) => {
        setQueryParams({
            ...queryParams,
            articleTitle: values.articleTitle,
            recommend: values.recommend,
            page: 1,
            limit: 10
        })
    }
    /**
     * 重置方法
     */
    const resetQueryParams = () => {
        queryForm.resetFields();
        setQueryParams(defaultQueryParams);
    }

    /**删除 */
    const removeHandler = async (articleId: number) => {
        Modal.confirm({
            title: '⚠️警告',
            content: '你确认执行改操作吗?',
            okText: '确认',
            cancelText: '取消',
            onOk: async () => {
                await deleteBeefTypeMutation({ articleId });
                refetch();
            },
        });
    };

    /**
     * !获取文章列表Hook
     */
    const { isLoading, isError, data: dataSource, error, refetch } = useGetArticle(queryParams);

    /**
     * !删除问这些HOOK
     */
    const { mutateAsync: deleteBeefTypeMutation, isLoading: DIsLoading } = useDeletedArticle();
    /**
        * 分页配置
        */
    const paginationProps = {
        total: dataSource?.count,
        pageSize: queryParams.limit,
        current: queryParams.page,
        showTotal: (count: number) => {
            return `共 ${count} 条`;
        },
        onChange: (pageNum: number) => {
            setQueryParams({ ...queryParams, page: pageNum });
        },
    };
    const columns = [
        {
            title: '文章ID',
            dataIndex: 'articleId',
            key: 'articleId',
        },
        {
            title: '文章标题',
            dataIndex: 'articleTitle',
            key: 'articleTitle',
        },
        {
            title: '文章标题图片',
            dataIndex: 'articleBanner',
            render(img: string | undefined) {
                if (img) {
                    return <img src={img} width="80" height="80" />
                }
                return "暂无图片"
            }
        },
        {
            title: '是否推荐',
            dataIndex: 'recommend',
            render(recommend: number) {
                if (recommend === 1) {
                    return "是"
                }
                return "否"
            }
        },
        {
            title: '发布单位',
            dataIndex: 'unitName',
            key: 'unitName',
        },
        {
            title: '观看次数',
            dataIndex: 'watchTime',
            key: 'watchTime',
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
        },
        {
            title: '更新时间',
            dataIndex: 'updateTime',
            key: 'updateTime',
        },
        {
            title: '更多操作',
            render(project: IArticle) {
                return (
                    <div>
                        <Button
                            style={{ marginRight: '1.2rem' }}
                            onClick={() => {
                                setUpdateArticle(project);
                                setOpen(true);
                            }}
                        >
                            修改
                        </Button>
                        <Button
                            loading={DIsLoading}
                            danger
                            onClick={() => removeHandler(project.articleId)}
                        >
                            删除
                        </Button>
                    </div>
                );
            },
        },
    ];
    return <BaseContiner>
        <TableHeader>
            <Form
                form={queryForm}
                style={{ width: '100%' }}
                onFinish={onFinish}
                autoComplete="off"
            >
                <Row gutter={16}>
                    <Col span={10}>
                        <Form.Item label="文章标题" name="articleTitle" >
                            <Input />
                        </Form.Item>
                    </Col>
                    <Col span={10}>
                        <Form.Item >
                            <Space>
                                <Button type="primary" htmlType="submit">
                                    搜索
                                </Button>
                                <Button type="primary" onClick={() => resetQueryParams()}>
                                    重置
                                </Button>
                            </Space>
                        </Form.Item>
                    </Col>
                    <Col span={4}>
                        <Flex gap="small" justify="flex-end">
                            <Button type="primary" icon={<PlusOutlined />} onClick={() => {
                                if (FormRef.current?.reset) {
                                    FormRef.current?.reset();
                                }
                                setUpdateArticle(undefined)
                                setOpen(true);
                            }}>
                                添加
                            </Button>
                        </Flex>
                    </Col>
                </Row>
            </Form>
        </TableHeader>
        <TableContainer>
            {isError ? (
                <ErrorBox error={error as { message: string }} />
            ) : (
                <Table
                    rowSelection={{ type: 'checkbox' }}
                    pagination={paginationProps}
                    dataSource={dataSource?.list}
                    columns={columns}
                    loading={isLoading}
                    rowKey={(row) => row?.articleId}
                />
            )}
        </TableContainer>
        <ArticleForm open={open} onRef={FormRef} openFn={openFn} refetch={refetch} article={updateArticle} />
    </BaseContiner>
}



export default memo(ArticlePage);